package com.sneaker.shower.controller;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.sneaker.shower.common.BaseView;
import com.sneaker.shower.entity.dto.WxPayParamDTO;
import com.sneaker.shower.service.PayService;
import com.sneaker.shower.util.JacksonUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


@RestController
@Slf4j
public class WxPayController {
    private final PayService payService;

    public WxPayController(PayService payService) {
        this.payService = payService;
    }


    @PostMapping(value = "/wx_pay/callBack")
    public void callBack(HttpServletResponse response, @RequestBody String xmlData) {
        try {
            synchronized (this) {
                String result = payService.callBack(xmlData);
                response.getWriter().write(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @PostMapping(value = "/wx_pay/pay_info")
    @ApiOperation(value = "微信统一下单，订单支付时 入参为/order/try_pay接口返回参数， 用户充值时，入参为 /user/charge接口返回参数")
    public BaseView<WxPayMpOrderResult> payInfo(@RequestBody WxPayParamDTO wxPayParamDTO) throws WxPayException {
        log.info("支付请求入参： {}", JacksonUtils.writeValueAsString(wxPayParamDTO));
        return new BaseView<>(payService.payInfo(wxPayParamDTO));
    }

    @ResponseBody
    @RequestMapping(value = "/wx_pay/rolling")
    public BaseView<Boolean> rolling(String guid) {
        return new BaseView<>(payService.isPaySuccess(guid));
    }

    @PostMapping("/wx_pay/close_order")
    public BaseView<Boolean> closeOrder(@RequestBody WxPayParamDTO wxPayParamDTO) {
        log.info("关闭支付请求入参:{}", JacksonUtils.writeValueAsString(wxPayParamDTO));
        return new BaseView<>(payService.closeOrder(wxPayParamDTO));
    }
}
